import os
import uuid
from datetime import datetime
from werkzeug.utils import secure_filename

UPLOAD_ROOT = 'uploads'


def save_image_file(file, user_id):
    # 获取当前时间戳字符串
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')

    # 生成唯一文件名
    filename = f"{timestamp}_{uuid.uuid4().hex[:8]}.jpg"

    # 磁盘保存目录：app/static/uploads/{user_id}/
    subfolder = os.path.join(STATIC_ROOT, "uploads", str(user_id))
    os.makedirs(subfolder, exist_ok=True)

    # 磁盘完整路径
    abs_path = os.path.join(subfolder, filename)
    file.save(abs_path)

    # 返回两个路径：1. 前端可用相对路径  2. 磁盘绝对路径
    rel_path = f"uploads/{user_id}/{filename}"
    return rel_path, abs_path



# Flask 内置的 static 目录
STATIC_ROOT = os.path.join(os.path.dirname(__file__), "..", "static")


def save_avatar(file, user_id):
    # 保留安全的文件名，统一用用户id命名，避免重复
    ext = file.filename.rsplit('.', 1)[-1].lower() if '.' in file.filename else "jpg"
    filename = secure_filename(f"{user_id}.{ext}")

    # 保存目录：app/static/avatars/
    subfolder = os.path.join(STATIC_ROOT, "avatars")
    os.makedirs(subfolder, exist_ok=True)

    # 最终路径（磁盘）
    file_path = os.path.join(subfolder, filename)
    file.save(file_path)

    # 数据库存储相对路径：avatars/xxx.jpg
    return f"avatars/{filename}"
